<template>
  <div class="upload-container">
    <!-- <el-form-item label="图片:" prop="img"> -->
    <el-upload
      class="avatar-uploader"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :on-success="handleAvatarSuccess"
      :headers="{ Authorization: token }"
      :action="requesturl()"
      :list-type="listType"
    >
      <div
        v-if="imageUrl"
        @mouseenter="deskHandler(0)"
        @mouseleave="deskHandler(1)"
      >
        <!-- 回显图片 -->
        <img
          :src="imageUrl"
          class="avatar"
        />

        <!-- 遮罩 -->
        <template v-if="needDesk">
          <div
            class="desk"
            v-show="showDesk"
          >
            <!-- 预览图标 -->
            <span
              class="upload-icon-father"
              @click.stop="preview"
            >
              <i class="el-icon-zoom-in icon"></i>
            </span>
            <!-- 删除图标 -->
            <span
              class="upload-icon-father"
              v-if="doWithoutDelete"
              @click.stop="removeImg"
            >
              <i class="el-icon-delete icon"></i>
            </span>
          </div>
        </template>
      </div>
      <!-- 上传图标 -->
      <div v-else>
        <i class="el-icon-plus avatar-uploader-icon"></i>
        <div class="upload-text">
          <slot name="uploadText"></slot>
        </div>
      </div>
    </el-upload>
    <!-- 底部提示文本 -->
    <span
      v-if="showInfo"
      class="text-info ele-text-secondary"
    >
      {{ info }}
    </span>
    <!-- 预览弹窗 -->
    <el-dialog :visible.sync="previewDialogVisable">
      <img
        width="100%"
        :src="imageUrl"
        alt=""
      />
    </el-dialog>
  </div>
</template>
<script>
import { getToken} from '@/utils/token-util';

export default {
  name: "my-upload-img",
  model: {
    prop: "imageUrl",
    event: "on-change",
  },
  props: {
    // 图片上传地址
    imageUrl: String,
    listType: {
      type: String,
      default: "text",
    },
    // 是否显示提示消息
    showInfo: {
      type: Boolean,
      default: true,
    },
    // 提示消息
    info: {
      tyepe: String,
      default: " 上传最佳体验比例为：380 X 240",
    },
    // 上传类型
    types: {
      tyepe: Array,
      default: null,
    },
    // 是否限制上传图片分辨率
    isSize: {
      type: Boolean,
      default: false,
    },
    // 限制上传分表率宽高
    size: {
      type: Object,
      width: {
        type: Number,
      },
      height: {
        type: Number,
      },
    },
    // 是否需要遮罩
    needDesk: {
      type: Boolean,
      default: false,
    },
    // 是否需要删除
    doWithoutDelete: {
      type: Boolean,
      default: true,
    },
    // 是否只读
   /*  readOnly: {
      type: Boolean,
      default: false,
    }, */
  },
  components: {},
  data() {
    return {
      // 是否显示遮罩
      showDesk: false,
      // 是否开启预览弹窗
      previewDialogVisable: false,
      token: getToken(),
    };
  },
  created() {
  },
  methods: {
    // 上传之前回调
    async beforeAvatarUpload(file) {
      console.log(file);
      let types = this.types || ["image/jpeg", "image/jpg", "image/png"];
      const isImage = types.includes(file.type);
      const isLt3M = file.size / 1024 / 1024 < 5;
      if (!isImage) {
        this.$message.error("请上传正确的格式!");
      }
      if (!isLt3M) {
        this.$message.error("上传图片大小不能超过 5MB!");
      }
      let isSize = this.isSize;
      if (isSize) {
        isSize = await this.checkImageWH(
          file,
          this.size.width,
          this.size.height
        );
        if (!isSize) {
          this.$message.error("上传图片分辨率不符!");
        }
      }
      isSize = this.isSize ? isSize : true;
      let res = isImage && isLt3M && isSize;
      return res || new Promise();
    },

    // 上传图片尺寸限制
    checkImageWH(file, width, height) {
      const isSize = new Promise(function (resolve) {
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function () {
          let valid = img.width <= width && img.height <= height;
          valid ? resolve(true) : resolve(false);
        };
        img.src = _URL.createObjectURL(file);
      });
      return isSize;
    },
    // 上传成功回调
    handleAvatarSuccess(res) {
      if (res.code == 0) {
        this.$emit("on-change", res.data.url);
      } else {
        this.$message.warning("上传失败，请稍后再试");
      }
    },
    // 移除图片
    removeImg() {
      this.$emit("on-change", null);
    },
    // 预览图片
    preview() {
      this.previewDialogVisable = true;
    },
    // 鼠标移入移出
    deskHandler(val) {
      val ? (this.showDesk = false) : (this.showDesk = true);
    },
    requesturl() {
      return process.env.VUE_APP_API_BASE_URL + "/file/upload";
      // return "http://agent.admin.creditcctv.cn/api/file/upload";
    },
  },
  computed: {},
};
</script>

<style lang='scss' scoped>
.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader :deep(.el-upload):hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.desk {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(8, 8, 8, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  & .upload-icon-father:nth-child(2) {
    margin-left: 10px;
  }
  .icon {
    font-size: 20px;
    z-index: 999;
    color: red;
  }
}
</style>
